package com.azxc.rapid.auth.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author linym
 * @create-day 2018-08-14 10:26
 */
@Slf4j
public class CheckSign {

    public static boolean checkSign(String SECRET_KEY,Map<String,String> params,String sendSign){
        //https://trade.zb.cn/api/order?accesskey=youraccesskey&amount=1.502/&currency=qtum_usdt&method=order&price=1.9001&tradeType=1
        String digest = EncryptUtils.encodeSHAString(SECRET_KEY);
        String reqeustSortStr=MapSort.toStringMap(params);
        String sign = null;
        try {
            sign = EncryptUtils.encodeHMACMD5String(digest,reqeustSortStr);
        } catch (Exception e) {
            log.error("Api校验签名错误！："+e.toString());
        }
        return sendSign.equals(sign)?true:false;
    }

    public static String getSign(String SECRET_KEY,String url){
        String[] param=url.substring(url.indexOf("?")+1).split("&");
        Map<String,String> pmap=new HashMap();
        for (String key : param) {
            if(key.indexOf("sign")!=-1){
                 continue;
            }
            String[] tmp=key.split("=");
            pmap.put(tmp[0],tmp[1]==null?"":tmp[1]);
        }
       // System.out.println(pmap);
        String digest = EncryptUtils.encodeSHAString(SECRET_KEY);
        //System.out.println("digest:"+digest);
        String reqeustSortStr=MapSort.toStringMap(pmap);
        //System.out.println(reqeustSortStr);
        String sign = null;
        try {
            sign = EncryptUtils.encodeHMACMD5String(digest,reqeustSortStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sign;
    }

    public static String  ASCIISort(String str) throws UnsupportedEncodingException {
        //str=java.net.URLEncoder.encode(str, "UTF-8");
        System.out.println(str);
        String[] param=str.split("&");
        Map<String,String> pmap=new HashMap();
        for (String key : param) {
            String[] tmp=key.split("=");
            pmap.put(tmp[0],tmp.length==1?"":java.net.URLEncoder.encode(tmp[1], "UTF-8"));
        }
        String reqeustSortStr=MapSort.toStringMap(pmap);
        return reqeustSortStr;
    }

    public static String SignNoSort(String SECRET_KEY,String url) throws UnsupportedEncodingException {
        String reqeustSortStr=ASCIISort(url);
        String digest = EncryptUtils.encodeSHAString(SECRET_KEY);
        String sign = null;
        try {
            sign = EncryptUtils.encodeHMACMD5String(digest,reqeustSortStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sign;
    }



    public static boolean checkSign(Map<String, String> map, String sendSign, String SECRET_KEY) {
        if(map.size()==0){
            //没有参数！
           return false;
        }
        String ACCESS_KEY=map.get("accesskey");
        if(Strings.isBlank(ACCESS_KEY)){
            return false;
        }
        try{
            boolean check= CheckSign.checkSign(SECRET_KEY,map,sendSign);
            if(!check){
                return false;
            }
        }
        catch (Exception ex){
            return false;
        }
        return true;
    }


    /*public static void main(String[] args){

        String ACCESS_KEY = "d0317f3288";
        String SECRET_KEY = "1614dfa7008241919e1bb7e76ea6f19f";
        String access_token="access_token";
		Map<String, String> params = new HashMap();
		//放置对应参数
		Long timestamp=System.currentTimeMillis();
		params.put("access_token", access_token);
		params.put("timestamp", String.valueOf(timestamp));
		params.put("appId", "d0317f3288");
		String sk="asdfsafasdfasdfasdfasdfa";
		String url="http://10.8.0.130:8090/rapid-sso/oauth/getUserInfoDto?access_token="+access_token;
		url+="&timestamp="+timestamp;
		url+="&appId=d0317f3288";

		String sign2= CheckSign.getSign(sk,url);
		params.put("signature", sign2);
        String digest = EncryptUtils.encodeSHAString(SECRET_KEY);
        log.info("SECRET_KEY:"+SECRET_KEY);
        log.info("change:"+digest);
        // 参数按照ASCII值排序
        // (首先比较参数名的第一个字母，按abcdefg顺序排列，若遇到相同首字母，则看第二个字母，以此类推)
        String reqeustSortStr=MapSort.toStringMap(params);
        String sign = null;
        try {
            sign = EncryptUtils.encodeHMACMD5String(digest,reqeustSortStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //String method = params.get("method").toString();
        //log.info("sign:"+"accesskey=6d8f62fd-3086-46e3-a0ba-c66a929c24e2&method=getAccountInfo");
        log.info("加密后得到的sign:"+sign);
        String url3="http://10.8.0.130:8090/rapid-sso/oauth/getUserInfoDto?access_token=&sign="
			+"&timestamp="+timestamp
		+"&appId=d0317f3288"+"&sign="+sign;
        *//*String getS= getSign(SECRET_KEY,url3);
        log.info("getSign:"+getS);*//*

       boolean r= checkSign(params,sign,SECRET_KEY);
        log.info("r:"+r);
    }*/

}
